*This file creates Upstream and downstream Leontief measures for the reparations schock. See the paper for details. 


*Imoport isic to isic2 key for 1970
import excel "$path\correspondence_io_isic2_isic.xlsx", sheet("Sheet1") firstrow clear

*Fix some industry links
drop if sector==106
replace isic2=7112 if isic=="712"
replace isic2=9511 if isic=="890"
rename isic ind39
tostring isic2, replace
gen toimiala_3=substr(isic2,1,3)
keep toimiala_3 ind39
duplicates drop ind39, force
tempfile correspond
save `correspond'


*Import leontief measures matrix
use "$path\downstream_leontief.dta" , clear

preserve
keep isic
gen ind=_n
tempfile key
rename isic ind39
save `key'
restore


preserve
use  "$temp\repadata_scaled.dta" ,clear
rename ind39 isic
destring isic, replace
keep isic repa_scaled
keep if repa_scaled>0
rename isic isic_2d
tempfile repa
save `repa'

restore

reshape long B, i(isic) j(ind)
joinby ind using `key'
drop ind 

rename ind39 isic2
rename isic ind39
rename isic2 isic

joinby ind39 using  `correspond'

destring ind39 isic, replace
rename B D
levelsof ind, local(levels)


*Fix industry links
replace ind39=3 if ind39==4

replace ind39=4 if ind39==2

replace ind39=2 if ind39==3

****
*Shock goes to isic industry. 
*****
replace D=D-1 if isic==ind39

tempfile ds
save `ds'


use "$path\upstream_leontief.dta" , clear

preserve
keep isic
gen ind=_n
tempfile key
rename isic ind39
save `key'
restore

reshape long B, i(isic) j(ind)

joinby ind using `key'
drop ind 

joinby ind39 using  `correspond'


destring ind39 isic, replace
rename B U
levelsof ind, local(levels)

replace U=U-1 if isic==ind39

drop ind39

joinby  isic toimiala_3 using `ds'

*Join with the reparations shocks
tostring isic, replace
gen isic_2d=substr(isic,1,2)
destring isic_2d, replace
joinby isic_2d using `repa', unmatched(master)


collapse  repa_scaled (sum) U D, by(isic_2d toimiala_3)

gen U_repa=repa_scaled*U
gen D_repa=repa_scaled*D

*Aggreagate to the 3-digit level
collapse (sum) U_repa D_repa U D , by(toimiala_3)


 save "$temp\upstream_downstream_toimiala3.dta", replace
